//
//  WBUserAccount.swift
//  新浪微博
//
//  Created by 名品导购网MPLife.com on 2017/11/29.
//  Copyright © 2017年 sweet. All rights reserved.
//

import UIKit

private let accountFile:NSString = "useraccount.json"
class WBUserAccount: NSObject {
    //访问令牌
   @objc dynamic var access_token: String?
    //用户代号
   @objc dynamic var uid: String?
    //过期日期 单位秒
    //开发者是五年。 每次登陆之后都是五年
    //使用者三天 会从第一次登录递减
    //基本数据类型，赋初始值
    //过期日期
    @objc var expiresDate:Date?
    @objc var screen_name:String?
    //用户头像地址
    @objc var avatar_large:String?
    
    
    @objc dynamic var expires_in : TimeInterval = 0 {
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    override var description: String{
        return yy_modelDescription()
    }
    override init() {
        super .init()
        //从磁盘加载保存的文件-》得到字典
        //加载磁盘文件到二进制数据 如果失败直接返回
        guard let path = accountFile.cz_appendDocumentDir(),let data = NSData(contentsOfFile: path), let dict = try? JSONSerialization .jsonObject(with: data as Data, options: []) as? [String:AnyObject] else {
            return
        }
     //从沙盒加载用户信息
        //使用字典设置属性值
        //设置用户是否登录的开关
        yy_modelSet(with: dict ?? [:])
        //判断token是否过期
        
        /*
         orderedDescending 降序
 */
//        expiresDate = Date(timeIntervalSinceNow: -3600*24)
//        print(expiresDate)
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            //清空token
            access_token = nil
            uid = nil
            //删除账户文件
            
            _ = try? FileManager .default.removeItem(atPath: path)
            
            
        }
        print("账户正常")
    }
    /*
     1.偏好设置
     2.沙盒-归档/plist/json
     3.数据库（FMDB/coreData）
     4.钥匙串访问 自动加密 需要使用框架 sskeychain
 */
    func saveAccount() {
        //模型转字典
        var dict = self.yy_modelToJSONObject() as? [String:AnyObject] ?? [:]
        dict .removeValue(forKey: "expires_in")
        
        //删除expires_in
        //字典序列化，就是转json
       
        guard let data = try? JSONSerialization .data(withJSONObject: dict, options: []),let filePath =  accountFile.cz_appendDocumentDir() else {
            return
        }
        (data as NSData) .write(toFile: filePath, atomically: true)
//        print("用户账户保存成功\(filePath)")
        //写入磁盘
    }
}
